import express, { type Request, Response, NextFunction } from "express";
import { registerRoutes } from "./routes";
import { setupVite, serveStatic, log } from "./vite";

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use((req, res, next) => {
  const start = Date.now();
  const path = req.path;
  let capturedJsonResponse: Record<string, any> | undefined = undefined;

  const originalResJson = res.json;
  res.json = function (bodyJson, ...args) {
    capturedJsonResponse = bodyJson;
    return originalResJson.apply(res, [bodyJson, ...args]);
  };

  res.on("finish", () => {
    const duration = Date.now() - start;
    if (path.startsWith("/api")) {
      let logLine = `${req.method} ${path} ${res.statusCode} in ${duration}ms`;
      if (capturedJsonResponse) {
        logLine += ` :: ${JSON.stringify(capturedJsonResponse)}`;
      }

      if (logLine.length > 80) {
        logLine = logLine.slice(0, 79) + "…";
      }

      log(logLine);
    }
  });

  next();
});

(async () => {
  const server = await registerRoutes(app);

  app.use((err: any, _req: Request, res: Response, _next: NextFunction) => {
    const status = err.status || err.statusCode || 500;
    const message = err.message || "Internal Server Error";

    res.status(status).json({ message });
    throw err;
  });

  // importantly only setup vite in development and after
  // setting up all the other routes so the catch-all route
  // doesn't interfere with the other routes
  if (app.get("env") === "development") {
    await setupVite(app, server);
  } else {
    serveStatic(app);
  }

  // ALWAYS serve the app on port 5000
  // this serves both the API and the client.
  // It is the only port that is not firewalled.
  const port = 5000;
  server.listen({
    port,
    host: "0.0.0.0",
    reusePort: true,
  }, () => {
    log(`serving on port ${port}`);
    
    // 启动测试后端服务器
    startTestServers();
    
    log("=== FRP 代理管理系统已启动 ===");
    log("测试后端服务器: localhost:3001, localhost:3002, localhost:3003");
    log("管理界面: http://localhost:5000");
  });

// 启动测试后端服务器
function startTestServers() {
  const testServers = [
    { name: 'server1', port: 3001 },
    { name: 'server2', port: 3002 },
    { name: 'server3', port: 3003 }
  ];

  testServers.forEach(({ name, port }) => {
    const testApp = express();
    testApp.use(express.json());

    // 健康检查端点
    testApp.get('/health', (req, res) => {
      res.json({ status: 'healthy', server: name, port, timestamp: new Date().toISOString() });
    });

    // 主页
    testApp.get('/', (req, res) => {
      res.json({ 
        message: `欢迎访问${name}`, 
        server: name,
        port,
        timestamp: new Date().toISOString(),
        clientIP: req.ip
      });
    });

    // API端点
    testApp.get('/api/users', (req, res) => {
      const users = {
        server1: [{ id: 1, name: '张三', server: name }, { id: 2, name: '李四', server: name }],
        server2: [{ id: 3, name: '王五', server: name }, { id: 4, name: '赵六', server: name }],
        server3: [{ id: 5, name: '孙七', server: name }, { id: 6, name: '周八', server: name }]
      };
      res.json(users[name] || []);
    });

    testApp.get('/api/status', (req, res) => {
      res.json({
        server: name,
        port,
        uptime: process.uptime(),
        memory: process.memoryUsage(),
        timestamp: new Date().toISOString()
      });
    });

    try {
      testApp.listen(port, '0.0.0.0', () => {
        log(`测试服务器 ${name} 运行在端口 ${port}`);
      });
    } catch (error) {
      log(`启动测试服务器 ${name} 失败: ${error}`);
    }
  });
}
})();
